# -*- coding: UTF-8 -*-
import pandas as pd
import os
import tkinter as tk
from tkinter.ttk import Combobox
from tkinter import filedialog
from tkinter import messagebox
import Class_Ploting as cpl
import json
import dict as dt

class Sample:
    #判断源文件是哪一种曲线
    def Check_DF_Type(self,RawDf):
        if r'效率/%' in RawDf:
            print("CNP")
            print('是否已预填写活性质量：',self.checkMass('放电比容量/mAh/g'))
            if self.checkMass('放电比容量/mAh/g'):
                self.originMass = round((self.RawDF['放电容量/mAh'][1] / self.RawDF['放电比容量/mAh/g'][1] * 1000),3)
                self.Mass = self.originMass
                print(self.Mass)
            return "CNP"
        elif r'比容量/mAh/g' in RawDf:
            if len(RawDf[RawDf[r'电压/V'] < 0]) > 200:
                print("LSC")
                print('是否已预填写活性质量：',self.checkMass('比容量/mAh/g'))
                return "LSC"
            else:
                if self.checkMass('比容量/mAh/g'):
                    self.originMass = round((self.RawDF['容量/mAh'][100] / self.RawDF['比容量/mAh/g'][100] * 1000), 3)
                    self.Mass = self.originMass
                    print(self.Mass)
                print('是否已预填写活性质量：',self.checkMass('比容量/mAh/g'))
                print("C_V")
                return "C_V"
    #检查是否填写了活性物质量
    def checkMass(self,title):
        if len(self.RawDF[self.RawDF[title] == 0]) == len(self.RawDF[title]):
            self.preMass = False
            return False
        else:
            self.preMass = True
            return True

    #找到最大地横纵坐标
    def FindMinMax(self,RawDF):
        max_X, max_Y = 0 , 0
        if self.type == 'CNP':
            max_X = RawDF['循环序号'].max()
            max_Y = RawDF['放电比容量/mAh/g'].max()
        elif self.type == 'LSC':
            max_X = RawDF[r'测试时间/Sec'].max()
            max_Y = max(abs(RawDF[r'电压/V'].max()),abs(RawDF[r'电压/V'].min()))
        elif self.type == 'C_V':
            max_X = RawDF[r'比容量/mAh/g'].max()
            max_Y = RawDF[r'电压/V'].max()
        return max_X , max_Y

    #弹出设置每个样品的样式窗口
    def createSampleLayoutWin(self):
        global Layout_Parameters
        self.LayoutWin = tk.Toplevel()
        self.LayoutWin.title('设置样品'+str(self.count+1)+'样式')

        # 线条颜色Label
        if self.preMass:
            MassLabel = tk.Label(self.LayoutWin, text="设置活性物质质量/mg\n"+"(源文件已指定"+str(self.originMass)+r"mg)")
            MassEntryVar = tk.StringVar()
            MassEntryVar.set(self.Mass)
            MassEntryVar = tk.StringVar()
            MassEntryVar.set(self.Mass)
            MassEntry = tk.Entry(self.LayoutWin,textvariable=MassEntryVar)
        else:
            MassLabel = tk.Label(self.LayoutWin, text="活性物质质量/mg\n(源文件未指定)")
            if self.SetMassInApp:
                MassEntryVar = tk.StringVar()
                MassEntryVar.set(self.Mass)
            else:
                MassEntryVar = tk.StringVar()
            MassEntry = tk.Entry(self.LayoutWin,textvariable=MassEntryVar)
        MassLabel.pack()
        MassEntry.pack()

        #偏置label
        BiasLabel = tk.Label(self.LayoutWin, text='以第几圈为首圈')
        BiasLabel.pack()
        BiasEntryVar = tk.StringVar()
        if self.bias:
            BiasEntryVar.set(self.bias)
        BiasEntry = tk.Entry(self.LayoutWin,textvariable=BiasEntryVar)
        BiasEntry.pack()

        #线条颜色Label
        LineColorLabel = tk.Label(self.LayoutWin, text="线条颜色")
        LineColorLabel.pack()
        #线条颜色Combobox
        LineColors = []
        for SL in SamepleLayoutList['LineColors']:
            LineColors.append(dt.dictionary[SL])
        LineColor = tk.StringVar()
        LineColor.set(dt.dictionary[self.Line_Color])
        LineColorCombobox = Combobox(self.LayoutWin,textvariable=LineColor,value=LineColors)
        LineColorCombobox.pack()

        #marker Label
        markerLabel = tk.Label(self.LayoutWin, text="marker样式")
        markerLabel.pack()
        #marker Combobox
        markers = []
        for SL in SamepleLayoutList['marker_styles']:
            markers.append(dt.dictionary[SL])
        marker = tk.StringVar()
        marker.set(dt.dictionary[self.Marker_Style])
        markerCombobox = Combobox(self.LayoutWin,textvariable=marker,value=markers)
        markerCombobox.pack()

        #线条类型Label
        LineStyleLabel = tk.Label(self.LayoutWin, text="线条样式")
        LineStyleLabel.pack()
        #线条类型 Combobox
        #LineStyles = SamepleLayoutList['line_styles']
        LineStyles = []
        for SL in SamepleLayoutList['line_styles']:
            LineStyles.append(dt.dictionary[SL])
        LineStyle = tk.StringVar()
        LineStyle.set(dt.dictionary[self.Line_Style])
        LineStyleCombobox = Combobox(self.LayoutWin,textvariable=LineStyle,value=LineStyles)
        LineStyleCombobox.pack()
        #点保存按钮的事件
        def save_single_sample_LCM():
            def is_number(s):
                try:  # 如果能运行float(s)语句，返回True（字符串s是浮点数）
                    float(s)
                    return True
                except ValueError:  # ValueError为Python的一种标准异常，表示"传入无效的参数"
                    pass  # 如果引发了ValueError这种异常，不做任何事情（pass：不做任何事情，一般用做占位语句）
                try:
                    import unicodedata  # 处理ASCii码的包
                    unicodedata.numeric(s)  # 把一个表示数字的字符串转换为浮点数返回的函数
                    return True
                except (TypeError, ValueError):
                    pass
                return False
            self.Line_Color = dt.dictionary[LineColor.get()]
            self.Marker_Style = dt.dictionary[marker.get()]
            self.Line_Style = dt.dictionary[LineStyle.get()]
            if self.type != 'LSC':
                if is_number(MassEntryVar.get()):
                    if round(float(MassEntryVar.get()),3) != self.Mass:
                        self.Mass = round(float(MassEntryVar.get()),3)
                        self.SetMassInApp = True
                        print(self.Mass)
                        if self.type == 'CNP':
                            self.RawDF['放电比容量/mAh/g'] = self.RawDF['放电容量/mAh'] / self.Mass * 1000
                            self.max_X, self.max_Y = self.FindMinMax(self.RawDF)
                        elif self.type == 'C_V':
                            self.RawDF['比容量/mAh/g'] = self.RawDF['容量/mAh'] / self.Mass * 1000
                            self.max_X, self.max_Y = self.FindMinMax(self.RawDF)
                    else:
                        print('设定前后质量相同')
                else:
                    messagebox.showinfo('警告', '请输入正确的值')
            if BiasEntryVar.get() != '':
                if is_number(BiasEntryVar.get()):
                    if int(BiasEntryVar.get()) > 1:
                        self.bias = int(BiasEntryVar.get())
                    else:
                        messagebox.showinfo('警告', '请输入正确的值')
                else:
                    messagebox.showinfo('警告', '请输入正确的值')
            else:
                self.bias = False
                print("inai")
            self.LayoutWin.destroy()

        SaveButton = tk.Button(self.LayoutWin, text='保存', command=save_single_sample_LCM)
        SaveButton.pack()
        return

    def __init__(self,path,count,LocatedWin):
        global SamepleLayoutList , Layout_Parameters
        self.count = count
        self.path = path
        self.filename = os.path.split(path)[-1].split('.')[0]
        self.RawDF = pd.read_csv(self.path,encoding="gbk")
        self.type = self.Check_DF_Type(self.RawDF)
        self.max_X , self.max_Y = self.FindMinMax(self.RawDF)
        self.SetMassInApp = False
        self.bias = False
        #读取样式属性
        self.Line_Color = Layout_Parameters['colors'][self.count]
        self.Marker_Style = Layout_Parameters['marker_styles'][self.count]
        self.Line_Style = Layout_Parameters['line_styles'][self.count]
        #建立标签与输入框
        self.Label = tk.Label(LocatedWin,text='样品'+str(self.count+1)+'名称')
        self.Label.pack()
        self.name = tk.StringVar(LocatedWin)
        self.name.set(self.filename)
        self.NameEntry = tk.Entry(LocatedWin,width=14,textvariable=self.name)
        self.NameEntry.pack()
        #建立按钮
        self.SetLayoutButton = tk.Button(LocatedWin,
                                         text='样品'+str(self.count+1)+'设置',
                                         command = self.createSampleLayoutWin)
        self.SetLayoutButton.pack()

    def Delete(self):
        self.Label.destroy()
        self.NameEntry.destroy()
        self.SetLayoutButton.destroy()
        del self

def JsonToParameter(input):
    #判断读取的json是否数字
    def is_number(s):
        try:  # 如果能运行float(s)语句，返回True（字符串s是浮点数）
            float(s)
            return True
        except ValueError:  # ValueError为Python的一种标准异常，表示"传入无效的参数"
            pass  # 如果引发了ValueError这种异常，不做任何事情（pass：不做任何事情，一般用做占位语句）
        try:
            import unicodedata  # 处理ASCii码的包
            unicodedata.numeric(s)  # 把一个表示数字的字符串转换为浮点数返回的函数
            return True
        except (TypeError, ValueError):
            pass
        return False
    # 判断读取的json是否为list
    def is_list(l):
        if r',' in l:
            return True
        else:
            return False
    #"数字"转数字 "列表"转列表
    for key in input.keys():
        print(input[key])
        if is_number(input[key]):
            input[key] = float(input[key])
        elif is_list(input[key]):
            input[key] = input[key].split(',')

    return input
def readParameters(jsondir='layout.json'):
    global Layout_Parameters
    with open(jsondir, 'r') as jsonfile:
        Layout_Parameters_contents = jsonfile.read()
        Raw_Layout_Parameters = json.loads(Layout_Parameters_contents)
        Layout_Parameters = JsonToParameter(Raw_Layout_Parameters)
    return
#打开对话框选取文件
def ask_dir():
    global samples , samplecount
    file = filedialog.askopenfilename(initialdir=os.getcwd(), title='添加一个文件', filetypes=[('按照要求导出的csv文件', '.csv')])
    if file:
        samples.append(Sample(file,samplecount,win))
        filenames.append(os.path.split(file)[-1].split('.')[0])
        samplecount += 1
        csvs.set(filenames)
def del_dir():
    global filenames,samplecount,csvs,samples,lb_csvs
    chosen = lb_csvs.curselection()[0]
    samples[chosen].Delete()
    del samples[chosen],filenames[chosen]
    csvs.set(filenames)
    samplecount -= 1
    print(samples)
    # for sam in samples:
    #     sam.Delete()
    # samples=[]
    # filenames=[]
    # csvs.set([])
    # samplecount=0

def start_C_V_misson():
    global NF_text_C_V, wid_C_V, hei_C_V, x_lim_C_V, y_lim_C_V, win_C_V , Layout_Parameters , C_V_colorListBox_Var_list
    # 按下绘图按钮事件
    def draw_C_V():
        NumberFilter0 = NF_text_C_V.get().split(',')
        NumberFilter = [int(x) for x in NumberFilter0]
        if x_lim_C_V.get():
            xlim_C_V = [int(x) for x in x_lim_C_V.get().split(',')]
        else:
            xlim_C_V = False
        if y_lim_C_V.get():
            ylim_C_V = [int(x) for x in y_lim_C_V.get().split(',')]
        else:
            ylim_C_V = False

        cpl.draw_C_V_plt(samples,
                        NumberFilter=NumberFilter,
                        Layout_Parameters=Layout_Parameters,
                        width=float(wid_C_V.get()),
                        height=float(hei_C_V.get()),
                        xlim=xlim_C_V,
                        ylim=ylim_C_V
                        )

    def C_V_color_up():
        if C_V_colorListBox.curselection():
            nowchoose = C_V_colorListBox.curselection()[0]
            if nowchoose != 0:
                color_TEM = Layout_Parameters["C_Vcolors"][nowchoose-1]
                Layout_Parameters["C_Vcolors"][nowchoose-1] = Layout_Parameters["C_Vcolors"][nowchoose]
                Layout_Parameters["C_Vcolors"][nowchoose] = color_TEM
                color_TEM_var_list = C_V_colorListBox_Var_list[nowchoose-1]
                C_V_colorListBox_Var_list[nowchoose - 1] = C_V_colorListBox_Var_list[nowchoose]
                C_V_colorListBox_Var_list[nowchoose] = color_TEM_var_list
                C_V_colorListBox_Var.set(C_V_colorListBox_Var_list)
                C_V_colorListBox.selection_set(nowchoose-1)
                C_V_colorListBox.selection_clear(nowchoose)
        else:
            print("no color chosen")
        return
    def C_V_color_down():
        if C_V_colorListBox.curselection():
            nowchoose = C_V_colorListBox.curselection()[0]
            if nowchoose != len(Layout_Parameters["C_Vcolors"])-1:
                color_TEM = Layout_Parameters["C_Vcolors"][nowchoose+1]
                Layout_Parameters["C_Vcolors"][nowchoose+1] = Layout_Parameters["C_Vcolors"][nowchoose]
                Layout_Parameters["C_Vcolors"][nowchoose] = color_TEM
                color_TEM_var_list = C_V_colorListBox_Var_list[nowchoose + 1]
                C_V_colorListBox_Var_list[nowchoose + 1] = C_V_colorListBox_Var_list[nowchoose]
                C_V_colorListBox_Var_list[nowchoose] = color_TEM_var_list
                C_V_colorListBox_Var.set(C_V_colorListBox_Var_list)
                C_V_colorListBox.selection_set(nowchoose+1)
                C_V_colorListBox.selection_clear(nowchoose)
        else:
            print("no color chosen")
        return
        return

    if samples:
        #检测选择的文件
        for sam in samples:
            if sam.type !=  'C_V':
                messagebox.showinfo('警告', '含有非充放电曲线类型的文件'+str(sam.name.get()))
                return

        win_C_V = tk.Toplevel()
        win_C_V.title('绘画容量-电压曲线')
        win_C_V.geometry()
        # 指定的绘图圈数Label
        NF_textLabel = tk.Label(win_C_V, text="指定需要作图的循环圈数 用,分割")
        NF_textLabel.pack()
        # 指定的绘图圈数
        NF_text_C_V = tk.StringVar(win_C_V)
        NF_text_C_V.set('5,10,20')
        NF_text_C_V_entry = tk.Entry(win_C_V, font=('Arial', 14), textvariable=NF_text_C_V, width=8)
        NF_text_C_V_entry.pack()
        # 长度的bar
        wid_C_V = tk.StringVar(win_C_V)
        wid_C_V.set(6.5)
        wid_bar_C_V = tk.Scale(win_C_V, label='图表宽度', from_=1, to=10, orient=tk.HORIZONTAL, length=200, showvalue=1,
                               tickinterval=9, resolution=0.5, variable=wid_C_V)
        wid_bar_C_V.pack()
        # 高度的bar
        hei_C_V = tk.StringVar(win_C_V)
        hei_C_V.set(5)
        hei_bar_C_V = tk.Scale(win_C_V, label='图表宽度', from_=1, to=10, orient=tk.HORIZONTAL, length=200, showvalue=1,
                               tickinterval=9, resolution=0.5, variable=hei_C_V)
        hei_bar_C_V.pack()
        # X轴范围
        x_text_Label_C_V = tk.Label(win_C_V, text="x轴范围 格式为 最小值,最大值")
        x_text_Label_C_V.pack()
        # x轴范围entry
        x_lim_C_V = tk.StringVar(win_C_V)
        x_lim_C_V_entry = tk.Entry(win_C_V, font=('Arial', 14), textvariable=x_lim_C_V, width=8)
        x_lim_C_V_entry.pack()
        # Y轴范围
        y_text_Label_C_V = tk.Label(win_C_V, text="y轴范围 格式为 最小值,最大值")
        y_text_Label_C_V.pack()
        # y轴范围entry
        y_lim_C_V = tk.StringVar(win_C_V)
        y_lim_C_V_entry = tk.Entry(win_C_V, font=('Arial', 14), textvariable=y_lim_C_V, width=8)
        y_lim_C_V_entry.pack()

        #颜色调整区域
        color_Label_C_V = tk.Label(win_C_V, text="设置线条颜色")
        color_Label_C_V.pack()

        Up_C_V_Button = tk.Button(win_C_V, text=r" ↑ ", command=C_V_color_up)
        Up_C_V_Button.pack()

        C_V_colorListBox_Var = tk.StringVar()
        C_V_colorListBox_Var_list = []
        for untranslatedPara in Layout_Parameters['C_Vcolors']:
            C_V_colorListBox_Var_list.append(dt.dictionary[untranslatedPara])
        C_V_colorListBox_Var.set(C_V_colorListBox_Var_list)
        C_V_colorListBox = tk.Listbox(win_C_V, listvariable=C_V_colorListBox_Var,selectmode=tk.SINGLE)
        C_V_colorListBox.pack()

        Down_C_V_Button = tk.Button(win_C_V, text=r" ↓ ", command=C_V_color_down)
        Down_C_V_Button.pack()

        # 绘图按钮
        # 弹出容量-电压曲线子窗口按钮
        Draw_C_V_Button = tk.Button(win_C_V, text="绘画容量-电压曲线", command=draw_C_V)
        Draw_C_V_Button.pack()


    else:
        messagebox.showinfo('警告', '请选择csv文件')
        return
def start_CNP_misson():
    global wid_CNP, hei_CNP, x_lim_CNP, y_lim_CNP, win_CNP, suby_lim_CNP , Ymax
    #按钮事件
    def draw_CNP():
        global Ymax
        for sam in samples:
            if sam.SetMassInApp:
                if sam.max_Y > Ymax:
                    Ymax = sam.max_Y

        if y_lim_CNP.get() != '':
            y_lim_CNP_tem = [int(x) for x in y_lim_CNP.get().split(',')]
            ylimmax = y_lim_CNP_tem[1]
            ylimmin = y_lim_CNP_tem[0]
        else:
            ylimmax = Ymax*2
            ylimmin = False

        print(y_lim_CNP.get())

        cpl.draw_CNP_plt(samples,
                        Layout_Parameters=Layout_Parameters,
                        xlim_max=int(x_lim_CNP.get()),
                        width=float(wid_CNP.get()),
                        height=float(hei_CNP.get()),
                        subymax=suby_lim_CNP.get(),
                        ylimmax=ylimmax,
                        ylimmin=ylimmin
                        )
        return

    Xmax , Ymax = 0 , 0
    if samples:
        #检测选择的文件
        for sam in samples:
            if sam.type !=  'CNP':
                messagebox.showinfo('警告', '含有非循环曲线类型的文件'+str(sam.name.get()))
                return
            if sam.max_X > Xmax:
                Xmax = sam.max_X
            if sam.max_Y > Ymax:
                Ymax = sam.max_Y

        win_CNP = tk.Toplevel()
        win_CNP.title('绘画长循环曲线')
        win_CNP.geometry('300x500+450+450')

        # 长度的bar
        wid_CNP = tk.StringVar(win_CNP)
        wid_CNP.set(8)
        wid_bar_CNP = tk.Scale(win_CNP, label='图表宽度', from_=1, to=10, orient=tk.HORIZONTAL, length=200, showvalue=1,
                               tickinterval=9, resolution=0.5, variable=wid_CNP)
        wid_bar_CNP.pack()

        # 高度的bar
        hei_CNP = tk.StringVar(win_CNP)
        hei_CNP.set(5)
        hei_bar_CNP = tk.Scale(win_CNP, label='图表宽度', from_=1, to=10, orient=tk.HORIZONTAL, length=200, showvalue=1,
                               tickinterval=9, resolution=0.5, variable=hei_CNP)
        hei_bar_CNP.pack()

        # x轴范围bar
        x_lim_CNP = tk.StringVar(win_CNP)
        x_lim_CNP.set(Xmax)
        x_lim_CNP_entry = tk.Scale(win_CNP, label='循环圈数范围', from_=0, to=Xmax, orient=tk.HORIZONTAL,
                                   length=300, showvalue=1, tickinterval=10, resolution=1, variable=x_lim_CNP)
        x_lim_CNP_entry.pack()
        # 主Y轴范围
        y_text_Label_CNP = tk.Label(win_CNP, text="（Y轴）比容量范围 格式为:最小值,最大值 不填写则默认")
        y_text_Label_CNP.pack()
        # 主y轴范围entry
        y_lim_CNP = tk.StringVar(win_CNP)
        y_lim_CNP.set('')
        y_lim_CNP_entry = tk.Entry(win_CNP, font=('Arial', 14), textvariable=y_lim_CNP, width=8)
        y_lim_CNP_entry.pack()

        # 副Y轴范围bar
        suby_lim_CNP = tk.StringVar(win_CNP)
        suby_lim_CNP.set(105)
        suby_lim_CNP_bar = tk.Scale(win_CNP, label='库伦效率坐标轴最大值', from_=0, to=120, orient=tk.HORIZONTAL, length=300,
                                    showvalue=1, resolution=1, variable=suby_lim_CNP)
        suby_lim_CNP_bar.pack()

        # 绘图按钮
        # 弹出容量-电压曲线子窗口按钮
        Draw_CNP_Button = tk.Button(win_CNP, text="绘画容量-圈数-效率曲线", command=draw_CNP)
        Draw_CNP_Button.pack()

    return
def start_LSC_misson():
    global Xmax_LSC, Ymax_LSC, Ymin_LSC, wid_LSC, hei_LSC, csvs, win_LSC
    #按钮事件
    def draw_LSC():
        cpl.draw_LSC_plt(samples,
                        Layout_Parameters=Layout_Parameters,
                        width=float(wid_LSC.get()),
                        height=float(hei_LSC.get()),
                        xlim=int(Xmax_LSC.get()),
                        ylimmax=float(Ymax_LSC.get()),
                        ylimmin=float(Ymin_LSC.get())
                        )
        return

    Xmax, Ymax = 0, 0
    if samples:
        # 检测选择的文件
        for sam in samples:
            if sam.type != 'LSC':
                messagebox.showinfo('警告', '含有非对称电池曲线类型的文件'+str(sam.name.get()))
                return
            if sam.max_X > Xmax:
                Xmax = sam.max_X
            if sam.max_Y > Ymax:
                Ymax = sam.max_Y

        win_LSC = tk.Toplevel()
        win_LSC.title('绘画对称电池')
        win_LSC.geometry('600x500+500+500')

        # 横坐标的bar
        Xmax_LSC = tk.StringVar(win_LSC)
        Xmax_LSC.set(Xmax / 3600)
        Xmax_Bar_LSC = tk.Scale(win_LSC, label='最大横坐标(Time / h)', from_=0, to=Xmax / 3600, orient=tk.HORIZONTAL,
                                length=600, resolution=1, variable=Xmax_LSC)
        Xmax_Bar_LSC.pack()
        # 纵坐标的bar max
        Ymax_LSC = tk.StringVar(win_LSC)
        Ymax_LSC.set(Ymax * 1.5)
        Ymax_Bar_LSC = tk.Scale(win_LSC, label='最大纵坐标（电位）', from_=0, to=Ymax * 4, orient=tk.HORIZONTAL, length=600,
                                resolution=0.05, variable=Ymax_LSC)
        Ymax_Bar_LSC.pack()
        # 纵坐标的bar min
        Ymin_LSC = tk.StringVar(win_LSC)
        Ymin_LSC.set(-Ymax * 1.5)
        Ymin_LSC_LSC = tk.Scale(win_LSC, label='最小纵坐标（电位）', from_=0, to=-Ymax * 4, orient=tk.HORIZONTAL, length=600,
                                resolution=0.05, variable=Ymin_LSC)
        Ymin_LSC_LSC.pack()

        # 调节图表长宽

        # 长度的bar
        wid_LSC = tk.StringVar(win_LSC)
        wid_LSC.set(8)
        wid_bar_LSC = tk.Scale(win_LSC, label='图表宽度', from_=1, to=10, orient=tk.HORIZONTAL, length=200, showvalue=1,
                               tickinterval=9, resolution=0.5, variable=wid_LSC)
        wid_bar_LSC.pack()

        # 高度的bar
        hei_LSC = tk.StringVar(win_LSC)
        hei_LSC.set(4)
        hei_bar_LSC = tk.Scale(win_LSC, label='图表宽度', from_=1, to=10, orient=tk.HORIZONTAL, length=200, showvalue=1,
                               tickinterval=9, resolution=0.5, variable=hei_LSC)
        hei_bar_LSC.pack()

        # 绘图按钮
        # 弹出容量-电压曲线子窗口按钮
        Draw_LSC_Button = tk.Button(win_LSC, text="绘画对称电池曲线", command=draw_LSC)
        Draw_LSC_Button.pack()
    else:
        messagebox.showinfo('警告', '请选择csv文件')
    return
def start_GITT_misson():
    messagebox.showinfo('开发中', '开发中，敬请期待')
    return
def Set_Layout_window():
    win_Layout = tk.Toplevel()
    Layout_labels = []
    Layout_Entrys = []
    Layout_Entrys_value = []
    Layout_Entrys_value_StringVar = []
    count = 0
    for x in Layout_Parameters.keys():
        Layout_labels.append(tk.Label(win_Layout, text=dt.dictionary[x]))
        Layout_labels[count].pack()
        Layout_Entrys_value.append(Layout_Parameters[x])
        Layout_Entrys_value_StringVar.append(tk.StringVar())
        if isinstance(Layout_Parameters[x], list):
            ListToStringTem = ""
            for x in Layout_Parameters[x]:
                ListToStringTem = ListToStringTem + x + ','
                Layout_Entrys_value_StringVar[count].set(ListToStringTem[:-1])
        else:
            Layout_Entrys_value_StringVar[count].set(Layout_Parameters[x])
        Layout_Entrys.append(tk.Entry(win_Layout, textvariable=Layout_Entrys_value_StringVar[count]))
        Layout_Entrys[count].pack()
        count += 1

    # 保存按钮事件
    def SaveLayout(jsondir='layout.json'):
        save_count = 0
        for key in Layout_Parameters.keys():
            Layout_Parameters[key] = Layout_Entrys_value_StringVar[save_count].get()
            if is_number(Layout_Parameters[key]):
                Layout_Parameters[key] = float(Layout_Parameters[key])
            save_count += 1
        with open(jsondir, 'w') as writeJSON:
            json.dump(Layout_Parameters, writeJSON, indent=4)
        readParameters()
        win_Layout.destroy()
        return

    # 重置按钮事件
    def ResetLayout(defaultJSON='default_layout.json', jsondir='layout.json'):
        with open(defaultJSON, 'r') as defaultjsonfile:
            Layout_Parameters_contents = defaultjsonfile.read()
        with open(jsondir, 'w') as writeJSON:
            writeJSON.write(Layout_Parameters_contents)
        readParameters()
        win_Layout.destroy()
        return

    def is_number(s):
        try:  # 如果能运行float(s)语句，返回True（字符串s是浮点数）
            float(s)
            return True
        except ValueError:  # ValueError为Python的一种标准异常，表示"传入无效的参数"
            pass  # 如果引发了ValueError这种异常，不做任何事情（pass：不做任何事情，一般用做占位语句）
        try:
            import unicodedata  # 处理ASCii码的包
            unicodedata.numeric(s)  # 把一个表示数字的字符串转换为浮点数返回的函数
            return True
        except (TypeError, ValueError):
            pass
        return False

    # 保存按钮
    Save_Layout_Button = tk.Button(win_Layout, text="保存样式", command=SaveLayout)
    Save_Layout_Button.pack()

    # 重置按钮
    Reset_Layout_Button = tk.Button(win_Layout, text="重置样式", command=ResetLayout)
    Reset_Layout_Button.pack()
    return
samples = []
samplecount = 0
filenames = []
if __name__ == '__main__':
    readParameters()
    SamepleLayoutList = json.loads(open('SamepleLayoutList.json', 'r').read())

    win = tk.Tk()
    win.title('LandTools')
    # file label
    filelabel = tk.Label(win, text="1.添加/移除csv文件")
    filelabel.pack()
    # 选择路径的按钮
    Ask_Dir_Button = tk.Button(win, text="添加csv文件", command=ask_dir)
    Ask_Dir_Button.pack()
    # 文件列表listbox
    csvs = tk.StringVar()
    lb_csvs = tk.Listbox(win, listvariable=csvs, height=4, width=15)
    lb_csvs.pack()
    # 删除CSV按钮
    Del_Dir_Button = tk.Button(win, text="移除选中文件", command=del_dir)
    Del_Dir_Button.pack()

    # missionLabel
    missionLabel = tk.Label(win, text="2.选择任务")
    missionLabel.pack()
    # 任务按钮：创建子窗口 用于画容量-电压曲线
    Open_C_V_Button = tk.Button(win, text="容量-电压曲线", command=start_C_V_misson)
    Open_C_V_Button.pack()
    # 任务按钮：创建子窗口 用于画容量-圈数-效率曲线
    Draw_CNP_Button = tk.Button(win, text="绘画长循环曲线", command=start_CNP_misson)
    Draw_CNP_Button.pack()
    # 任务按钮：创建子窗口 用于画对称电池曲线
    Draw_LSC_Button = tk.Button(win, text="对称电池曲线", command=start_LSC_misson)
    Draw_LSC_Button.pack()
    # 任务按钮：创建子窗口 用于GITT
    Draw_GITT_Button = tk.Button(win, text="GITT数据处理(开发中)", command=start_GITT_misson)
    Draw_GITT_Button.pack()

    # sxtraLabel
    sxtraLabel = tk.Label(win, text="*3.高级设置")
    sxtraLabel.pack()

    # 弹出样式表设置 按钮
    Layout_Button = tk.Button(win, text="设置图表样式", command=Set_Layout_window)
    Layout_Button.pack()

    win.mainloop()